from django.shortcuts import render, HttpResponse, redirect, reverse
from django.http import JsonResponse
import datetime
from django_redis import get_redis_connection
import json
from utils.encrypt import uid

from web import models


def index(request):
    return render(request, "index.html")


def price(request):
    """价格页面展示"""
    policy_list = models.PricePolicy.objects.filter(category=2)
    return render(request, "price.html", {"policy_list": policy_list})


def payment(request, policy_id):
    """订单信息展示页面"""
    policy_object = models.PricePolicy.objects.filter(id=policy_id, category=2).first()
    if not policy_object:
        return redirect("price")

    num = request.GET.get("number", "")
    if not num or not num.isdecimal():
        return redirect("price")

    num = int(num)
    if num < 1:
        return redirect("price")

    # 计算价格，当前用户所购买套餐金额
    origin_price = num * policy_object.price

    # 可抵扣金额，查看原来的订单，判断是否可以抵扣优惠
    balance = 0
    if request.tracer.price_policy.category == 2:
        # 找到之前的订单：总支付费用，开始日期，结束日期，剩余天数，
        _object = models.Transaction.objects.filter(user=request.tracer.user, status=2).order_by("-id").first()
        # 套餐总天数
        total_timedelta = _object.end_datetime - _object.start_datetime
        # 套餐到目前还剩余天数，可用于抵扣
        balance_timedelta = _object.end_datetime - datetime.datetime.now()
        if total_timedelta.days == balance_timedelta.days:
            # 套餐总天数=套餐目前剩余天数（意为用户刚购买套餐就又要升级套餐）
            balance = _object.price / total_timedelta.days * (balance_timedelta.days - 1)
        else:
            balance = _object.price / total_timedelta.days * balance_timedelta.days

        # 如果可抵扣金额大于当前购买套餐金额，就直接返回价格页面
        if balance > origin_price:
            return redirect("price")

    context = {
        "policy_id": policy_object.id,
        "number": num,
        "origin_price": origin_price,
        "balance": round(balance, 2),
        "total_price": origin_price - round(balance, 2)
    }

    context["policy_object"] = policy_object

    # 把订单信息保存到redis中
    conn = get_redis_connection()
    conn.set("context-{}".format(request.tracer.user.mobile_phone), context, ex=60 * 30)

    return render(request, "payment.html", json.dumps(context))


def pay(request):
    """订单支付"""
    # 从redis中获取订单信息
    conn = get_redis_connection()
    bytes_context = conn.get("context-{}".format(request.tracer.user.mobile_phone))
    if not bytes_context:
        return redirect("price")

    context = json.loads(bytes_context.decode("utf-8"))

    # 创建订单信息，交易记录
    models.Transaction.objects.create(
        status=1,
        order=uid(request.tracer.user.mobile_phone),
        user=request.tracer.user,
        price_policy=context["policy_object"],
        count=context["num"],
        price=context["total_price"],
    )
